package com.base.listener;

import com.base.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * <p>
 *     Redis初始化操作
 * <p>
 *
 * @author hys
 * @since 2024/4/11 11:21
 */
@Component
@Slf4j
public class RedisInitializer {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
    * @Description: 事件监听器，在springboot程序执行成功后回调这个方法，清除redis数据的操作
    * @Param:
    * @return:
    * @Author: zhou minghao
    * @Date: 8:40 2024/4/17
    */
    @EventListener(ApplicationStartedEvent.class)
    public void clearRedisOnInit() {
        //redisTemplate.execute(RedisCallback) 其中RedisCallback是redis连接成功的回调方法
        redisTemplate.execute((RedisConnection connection)->{
            //通过回调方法刷新redis
            connection.flushDb();
            return "redis数据刷新成功";
        });
        log.info("redis数据刷新成功");
    }

}
